﻿using System;
using System.Linq;
using System.Web.Http;
using FellowshipOne.API;
using FellowshipOne.API.Base;
using FellowshipOne.API.Events.Model;
using FellowshipOne.API.Events.QueryObject;
using MasVida.WebApi.Controllers.Interfaces;
using MasVida.WebApi.Models.DataObject;
using MasVida.WebApi.Models.Requests;
using MasVida.WebApi.Models.Responses;
using Newtonsoft.Json.Linq;

namespace MasVida.WebApi.Controllers
{
    public class AttendanceSummaryController : ApiBaseController
    {
        public AttendanceSummaryController()
        {
            
        }

        public AttendanceSummaryController(IRestClient restClient)
        {
            RestClient = restClient;
        }

        [HttpPost]
        public AttendanceSummaryResponse GetAttendanceSummaryByGroup(JObject jObject)
        {
            AttendanceSummaryRequest groupRequest = GetRequestFromJObject(jObject);

            AttendanceSummaryResponse response = new AttendanceSummaryResponse();
            try
            {
                IRestClient restClient = GetRestClient(groupRequest.AccessTicket);
                AttendanceSummaryQO query = new AttendanceSummaryQO { AttendanceContextValueId = groupRequest.GroupId, AttendanceContextTypeId = 1 };
                AttendanceSummaryCollection attendanceSummaryCollection = restClient.EventsRealm.AttendanceSummary.Search<AttendanceSummaryCollection>(query);
                response.AttendanceSummaries = attendanceSummaryCollection
                    .Where(a => (!groupRequest.StartDate.HasValue || a.StartDateTime >= groupRequest.StartDate.Value)
                        && (!groupRequest.EndDate.HasValue || a.StartDateTime <= groupRequest.EndDate.Value)
                    )
                    .Select(a => new AttendanceSummaryDO()
                {
                    AbsentCount = a.AbsentCount,
                    AttendanceSummaryId = a.ID ?? 0,
                    Comments = a.Comments,
                    CreatedDate = a.CreatedDate,
                    EndTime = a.EndDateTime,
                    IsPosted = a.IsPosted,
                    IsScheduled = a.IsScheduled,
                    Met = a.Met,
                    PresentCount = a.PresentCount,
                    StartTime = a.StartDateTime,
                    TotalCount = a.TotalCount
                });
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
            }
            return response;
        }

        [HttpPost]
        public AttendanceSummaryResponse UpdateAttendanceSummary(JObject jObject)
        {
            AttendanceSummaryRequest groupRequest = GetRequestFromJObject(jObject);
            AttendanceSummaryDO attendanceSummaryDo = groupRequest.AttendanceSummary;

            AttendanceSummaryResponse response = new AttendanceSummaryResponse();

            if (attendanceSummaryDo.TotalCount != attendanceSummaryDo.AbsentCount + attendanceSummaryDo.PresentCount)
            {
                response.ErrorMessage = "Counts do not match";
                return response;
            }
            try
            {
                IRestClient restClient = GetRestClient(groupRequest.AccessTicket);
                AttendanceSummary attendanceSummary = restClient.EventsRealm.AttendanceSummary.Get(attendanceSummaryDo.AttendanceSummaryId.ToString());
                attendanceSummaryDo.UpdateAttendanceSummary(attendanceSummary);

                restClient.EventsRealm.AttendanceSummary.Update(attendanceSummary, attendanceSummary.ID.ToString());
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
            }
            return response;
        }

        private AttendanceSummaryRequest GetRequestFromJObject(JObject jobject)
        {
            return new AttendanceSummaryRequest()
            {
                ApiKey = jobject["ApiKey"]?.Value<string>(),
                AccessTicket = jobject["AccessTicket"]?.ToObject<F1OAuthTicket>(),
                GroupId = jobject["GroupId"]?.Value<int>() ?? 0,
                StartDate = jobject["StartDate"]?.ToObject<DateTime?>(),
                EndDate = jobject["EndDate"]?.ToObject<DateTime?>(),
                AttendanceSummary = jobject["AttendanceSummary"]?.ToObject<AttendanceSummaryDO>()
            };
        }
    }
}